﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DeviceFinder.DAL;
using DeviceFinder.Models;
using System.IO;

namespace DeviceFinder.Controllers
{
    public class UserController : Controller
    {
        private UserDAL dal;

        public UserController()
        {
            dal = new UserDAL();
        }

        //
        // GET: /User/

        public ActionResult Index()
        {
            if (CheckAccount() != false)
            {
                Response.Redirect(Url.Content("~/User/TrackLog").ToString());
            }
            return View();
        }

        public ActionResult ChangeUserInfo()
        {
            CheckAccount();
            return View();
        }

        [HttpPost]
        public ActionResult ChangeUserInfo(UserModels model)
        {
            CheckAccount();
            if (ModelState.IsValid)
            {
                USER user = new USER();
                user.EMAIL = User.Identity.Name;
                user.PASSWORD = model.NewPassword;
                bool ret = dal.ChangeUserInfo(user, model.OldPassword);
                if (ret)
                {
                    ViewData["Result"] = "Successful!";
                }
                else
                {
                    ViewData["Result"] = "Failed!";
                }
            }
            else
            {
                ViewData["Result"] = "Invalid informations!";
            }

            return View(model);
        }

        public ActionResult DeviceChangeSettings(int ID)
        {
            CheckAccount();
            // ID of Device
            DeviceModel device = new DeviceModel();
            device.EmailUser = User.Identity.Name;

            DeviceDAL deviceDAL = new DeviceDAL();
            DEVICE dv = deviceDAL.GetDeviceByID(ID);

            device.Name = dv.NAME;
            device.Type = dv.TYPE;
            device.ID = ID;
            device.HomePage = dv.HOMEPAGE;
            if (dv.WEBCAM_CAPTURE != null)
                device.WebcamCapture = (int)dv.WEBCAM_CAPTURE;
            if (dv.IS_FOLLOW != null)
                device.IsFollow = (bool)dv.IS_FOLLOW;
            if (dv.IS_COMMAND_ACTIVE != null)
                device.IsActiveCommand = (bool)dv.IS_COMMAND_ACTIVE;
            if (dv.MESSAGE != null)
                device.Description = dv.MESSAGE;

            @ViewBag.ID = ID;

            return View(device);
        }

        [HttpPost]
        public ActionResult DeviceChangeSettings(DeviceModel model)
        {
            CheckAccount();
            if (ModelState.IsValid)
            {
                DeviceDAL deviceDAL = new DeviceDAL();
                bool ret = deviceDAL.ChangeDeviceInfo(model.ID, model.Name, model.IsFollow, model.IsActiveCommand, model.Description, model.WebcamCapture, model.HomePage);

                if (ret)
                {
                    Response.Redirect("~/User/ShowDevices");
                }
                else
                {
                    ViewData["Result"] = "Edit failed!";
                }
            }

            return View(model);
        }

        public ActionResult TrackLog()
        {
            CheckAccount();
            DeviceDAL deviceDAL = new DeviceDAL();
            string UserEmail = User.Identity.Name;

            List<DEVICE> devices = deviceDAL.GetAllDevices(UserEmail).ToList<DEVICE>();
            ViewBag.devices = devices;


            return View();
        }

        public ActionResult TrackLogForID(int ID)
        {
            CheckAccount();
            string userEmail = User.Identity.Name;

            DeviceDAL deviceDAL = new DeviceDAL();
            DEVICE checkDevice = deviceDAL.GetDeviceByID(ID);
            if (checkDevice.EMAIL_USER != userEmail)
                Response.Redirect(Url.Content("~/Account/Login"));


            TrackLogDAL trackLogDAL = new TrackLogDAL();
            ViewBag.trackLogList = trackLogDAL.GetTrackLogByID(ID).ToList<TRACKLOG>();

            return View();
        }

        // Show map tracklog theo ID Device
        public ActionResult ShowMapTrackLog(int ID)
        {
            CheckAccount();
            // ID = ID Device
            string userEmail = User.Identity.Name;

            DeviceDAL deviceDAL = new DeviceDAL();
            DEVICE checkDevice = deviceDAL.GetDeviceByID(ID);
            if (checkDevice.EMAIL_USER != userEmail)
                Response.Redirect(Url.Content("~/Account/Login"));


            TrackLogDAL trackLogDAL = new TrackLogDAL();
            ViewBag.trackLogList = trackLogDAL.GetTrackLogByID(ID).ToList<TRACKLOG>();

            return View();
        }

        public ActionResult HomePage(string ID)
        {
            ViewBag.ID = ID;
            return View();
        }

        [HttpPost]
        public ActionResult HomePage()
        {
            string latitude = Request.Form["lat"];
            string longtitude = Request.Form["long"];
            string ID = Request.Form["ID"];
            string IP = HttpContext.Request.ServerVariables["REMOTE_ADDR"];

            //ViewBag.respone = "Data receive " + latitude + " " + longtitude + " IP = " + IP;

            TrackLogDAL trackLongDAL = new TrackLogDAL();
            trackLongDAL.InsertLocationToID(int.Parse(ID), float.Parse(latitude), float.Parse(longtitude), IP, DateTime.Now);

            DeviceDAL deviceDAL = new DeviceDAL();
            DEVICE device = deviceDAL.GetDeviceByID(int.Parse(ID));
            ViewBag.respone = device.HOMEPAGE;


            return View();

        }

        public ActionResult AddDevice()
        {
            CheckAccount();
            DeviceModel device = new DeviceModel();
            device.EmailUser = User.Identity.Name;
            return View(device);
        }

        [HttpPost]
        public ActionResult AddDevice(DeviceModel model)
        {
            CheckAccount();
            int id;
            if (ModelState.IsValid && User.Identity.IsAuthenticated)
            {
                DeviceDAL deviceDal = new DeviceDAL();
                CreateDeviceStatus ret = deviceDal.CreateDevice(out id, model.EmailUser, model.Name, model.Type, model.IsFollow, model.HomePage, model.WebcamCapture, model.Description, model.IsActiveCommand);

                if (ret == CreateDeviceStatus.Success && id != -1)
                {
                    model.ID = id;
                    ViewBag.ID = id;
                    ViewData["Result"] = "Successful!";
                }
                else
                {
                    ViewData["Result"] = "Failed!";
                }
            }
            else
            {
                ViewData["Result"] = "Invalid input information!";
            }

            return View(model);
        }

        public ActionResult ShowDevices()
        {
            CheckAccount();
            string email = User.Identity.Name;
            DeviceDAL deviceDal = new DeviceDAL();
            List<DeviceShowModel> models = new List<DeviceShowModel>();
            var devices = deviceDal.GetAllDevicesInUse(email);
            foreach (DEVICE device in devices)
            {
                DeviceShowModel model = new DeviceShowModel();
                model.ID = device.IDDEVICE.ToString();
                model.Name = device.NAME;
                model.Type = device.TYPE;
                model.HomePage = device.HOMEPAGE;
                model.IsActiveCommand = (device.IS_COMMAND_ACTIVE == true) ? "x" : " ";
                model.IsFollow = (device.IS_FOLLOW == true) ? "x" : " ";
                model.WebcamCapture = (int)device.WEBCAM_CAPTURE;
                models.Add(model);
            }

            return View(models);
        }

        public ActionResult RemoveItem(string id)
        {
            CheckAccount();
            DeviceDAL deviceDal = new DeviceDAL();
            bool ret = deviceDal.DeleteDevice(int.Parse(id));
            Response.Redirect("~/User/ShowDevices");
            return View();
        }


        public ActionResult Message(string ID)
        {
            CheckAccount();
            ViewBag.ID = ID;
            return View();
        }

        public ActionResult CommandManager()
        {
            DeviceDAL deviceDAL = new DeviceDAL();
            string UserEmail = User.Identity.Name;

            List<DEVICE> devices = deviceDAL.GetAllDevices(UserEmail).ToList<DEVICE>();
            ViewBag.devices = devices;

            return View();
        }

        public ActionResult CommandList(int ID)
        {
            CheckAccount();
            string userEmail = User.Identity.Name;

            DeviceDAL deviceDAL = new DeviceDAL();
            DEVICE checkDevice = deviceDAL.GetDeviceByID(ID);
            if (checkDevice.EMAIL_USER != userEmail)
                Response.Redirect(Url.Content("~/Account/Login"));


            TrackLogDAL trackLogDAL = new TrackLogDAL();
            ViewBag.trackLogList = trackLogDAL.GetTrackLogByID(ID).ToList<TRACKLOG>();

            CommandDAL commandDAL = new CommandDAL();
            ViewBag.commandList = commandDAL.GetAllCommandByDeviceID(ID).ToList<COMMAND>();

            return View();
        }

        public ActionResult CommandAdd()
        {
            if (CheckAccount())
            {
                COMMAND cm = new COMMAND();
                cm.DATE = DateTime.Now;
                cm.IDDEVICE = int.Parse(Request["IDDevice"]);
                cm.OPCODE = Request["Opcode"];
                cm.PARAM = Request["Param"];
                cm.STATUS = "undone";

                CommandDAL cmDAL = new CommandDAL();
                if (cmDAL.AddCommand(cm))
                    ViewBag.Success = true;
                else
                    ViewBag.Success = false;

            }
            return View();
        }


        public ActionResult FileManager()
        {
            DeviceDAL deviceDAL = new DeviceDAL();
            string UserEmail = User.Identity.Name;

            List<DEVICE> devices = deviceDAL.GetAllDevices(UserEmail).ToList<DEVICE>();
            ViewBag.devices = devices;
            
            return View();
        }

        public FileContentResult GetFile(int ID)
        {
            UploadFileDAL upDAL = new UploadFileDAL();
            UPLOADFILE file = upDAL.GetFileByID(ID);
            string extension = Path.GetExtension(file.PATH);            
            FileContentResult result = new FileContentResult(file.DATA, extension);
            result.FileDownloadName = Path.GetFileName(file.PATH);
            return result;
        }

        public ActionResult GetFileList(int ID)
        {
            UploadFileDAL upDAL = new UploadFileDAL();
            ViewBag.Files = upDAL.GetAllFileByDeviceID(ID).ToList<UPLOADFILE>();

            return View();
        }

        private bool CheckAccount()
        {            
            if (!User.Identity.IsAuthenticated)
            {
                Response.Redirect(Url.Content("~/Account/Login"));
                return false;
            }
            return true;
        }
    }
}
